package com.hcloud.common.crud.aspect;

import com.hcloud.auth.api.permission.AuthorityCheckService;
import com.hcloud.common.core.base.HCloudResult;
import com.hcloud.common.crud.annon.HCloudPreAuthorize;
import com.hcloud.common.crud.controller.BaseDataController;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.file.AccessDeniedException;

/**
 * @Auther hepangui
 * @Date 2018/11/14
 */
@Aspect
@Component
public class PreAuthorizeAspect {

    @Autowired
    private AuthorityCheckService authorityCheckService;

    @Around("@annotation(hCloudPreAuthorize)")
    public Object around(ProceedingJoinPoint point, HCloudPreAuthorize hCloudPreAuthorize) throws Throwable {
        Object target = point.getTarget();
        if(target instanceof BaseDataController){
            BaseDataController baseDataController = (BaseDataController)target;
            String authPrefix = baseDataController.getAuthPrefix();
            String value = hCloudPreAuthorize.value();
            String authority = new StringBuilder(authPrefix).append(value).toString();
            boolean has = authorityCheckService.has(authority);
            if(has){
                return point.proceed();
            }else{
                HCloudResult hCloudResult = new HCloudResult("权限不足");
                hCloudResult.setCode(HCloudResult.NOAUTH);
                return hCloudResult;
            }

        }
        Object proceed = point.proceed();
        return proceed;
    }
}
